import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import intl from 'react-intl-universal';
import { Link } from 'react-router';
import Loading from 'components/Common/Loading';
import { Row, Col, Button, Table, Form, Select, Input, Popover, TimePicker } from 'antd';
import './style.scss';
import * as actions from 'action/shopping.js'
import RangeDatePicker from 'components/Common/RangeDatepicker';
import { getCurrentLocale, getCurrentDate, addDate, subtractDate, getDifferDays, CompareDate } from 'utils/tools';
import { getDate } from 'utils/date.js';
import Modal from 'components/Common/Modal';
import { message } from 'components/Common/message';
import moment from 'moment'

// import MyModal from 'components/MyModal';
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
const Status = {
  1: '待配送',
  2: '自取',
  3: '已配送',
  4: '取消配送'
}
let GLOBAL_LOCALES = {}
class List extends Component {
  constructor(props, context) {

    super(props, context);
    this.state = {
      loading: true,
      edit: false,
      startTime: '',
      endTime: '',
      value: '3',
      saveLoading: false,
      visible1: false,
      ary: []
    };



  }










  componentDidMount() {
    GLOBAL_LOCALES = {
      save: intl.get('lv.common.save'),
      cancel: intl.get('lv.common.cancel'),
    };
    this.props.actions.getHotelConfig(() => {
      this.setState({ loading: false, startTime: this.props.hotelDetail.startTime, endTime: this.props.hotelDetail.endTime, ary: JSON.parse(this.props.hotelDetail.commonProblem) })
    })
    this.props.actions.getSellerList()
  }



  componentWillUnmount() {

  }


  onStartChange = (time, timeStr) => {
    this.setState({
      startTime: timeStr
    })
  }
  commitChange1 = (callBack) => {
    this.props.actions.delSeller({ id: this.state.id },
      () => {
        this.setState({ visible1: false, id: null, loading: true }, () => {
          this.props.actions.getSellerList(() => this.setState({ loading: false }))
        })

      }, () => {
        callBack()
      })

  }
  commitChange2 = (callback) => {
    this.props.form.validateFields((error, values) => {
      if (!error) {
        let { sellerPhoneNumber, sellerName } = this.props.form.getFieldsValue();
        let params = { sellerPhoneNumber, sellerName };
        this.props.actions.addSeller(params, () => {
          this.setState({ visible2: false, loading: true }, () => {
            this.props.actions.getSellerList(() => this.setState({ loading: false }))
          })
        }, () => {
          callback && callback();
        })

      } else {
        callback && callback()
      }
    })
  }
  _renderTableColumns = () => {
    return [{
      title: '姓名',
      dataIndex: 'sellerName',
      key: 'sellerName',
      width: '40%',
    }, {
      title: '电话',
      dataIndex: 'sellerPhoneNumber',
      key: 'sellerPhoneNumber',
      width: '30%',
    }, {
      title: '操作',
      key: 'control',
      width: '30%',
      render: (text, record, index) => {
        return <div>

          <Link href={record.qrCodeUrl} target='_black' className='first' style={{ marginRight: '5px' }} onClick={() => {


          }}>
            <span >下载二维码</span>
          </Link>
          <Link className='first' onClick={() => {
            this.setState({ visible1: true, id: record.id })
          }}>
            <span>删除</span>
          </Link>
        </div>
      }
    }]
  }
  onEndChange = (time, timeStr) => {
    if (!this.state.startTime) {
      message.warn("请先选择起始时间")
    }
    if (moment(this.state.startTime, 'HH:mm').isBefore(time)) {
      this.setState({
        endTime: timeStr
      })
    } else {
      message.warn("请选择正确的值")
    }
  }


  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 18 },
        sm: { span: 18 },
      },
    };
    const formItemLayout1 = {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 21 },
        sm: { span: 21 },
      },
    };
    const { getFieldDecorator } = this.props.form;

    // if (this.props.children) {
    //   return <div>{this.props.children}</div>
    // }
    let operate, operate1;
    if (this.state.edit) {
      operate = (
        <div className="editBtnGroups">
          <Button size="default" type="primary" loading={this.state.saveLoading} onClick={() => {
            if (this.state.saveLoading) {
              return
            }
            this.setState({ loading: true, saveLoading: true }, () => {
              this.props.actions.updataConfig({
                startTime: this.state.startTime,
                endTime: this.state.endTime
              }, () => {
                this.setState({ edit: false, saveLoading: false }, () => {
                  this.props.actions.getHotelConfig(() => {
                    this.setState({ loading: false, startTime: this.props.hotelDetail.startTime, endTime: this.props.hotelDetail.endTime })
                  })
                })
              },()=>{
                this.setState({loading:false,saveLoading:false})
              })
            })
          }}>{GLOBAL_LOCALES['save']}</Button>
          <Button size="default" style={{ marginLeft: '10px' }} onClick={() => {
            this.setState({ edit: false, startTime: this.props.hotelDetail.startTime, endTime: this.props.hotelDetail.endTime })
          }}>{GLOBAL_LOCALES['cancel']}</Button>
        </div>
      );
    } else {
      operate = <div className="shopping-operate i-icon" onClick={() => {
        this.setState({ edit: true })
      }}>{intl.get('lv.common.button.edit')}</div>;
    }



    if (this.state.edit1) {
      operate1 = (
        <div className="editBtnGroups">
          <Button size="default" type="primary" loading={this.state.saveLoading1} onClick={() => {
            if (this.state.saveLoading1) {
              return
            }
            let obj=this.props.form.getFieldsValue();
              let params={};
              let flag=false;
              let ary=[]
              Object.keys(obj).map(item=>{
                if(item.split('-')[0]=='title'){
                  let obj1={};
                  if(obj[item]&&obj[item].replace('/s+','')){
                    obj1.title=obj[item];
                    obj1.indx=item.split('-')[1];
                    obj1.content=[];
                    ary.push(obj1)
                  }else{
                    flag=true;
                  }
                }
              })
              if(flag){
                message.warn('请完善常见内容')
                return
              }
              Object.keys(obj).map(item=>{
                if(item.split('-')[0]=='content'){
                 
                  let obj1={};
                  if(obj[item]&&obj[item].replace('/s+','')){
                    obj1.content=obj[item];
                    obj1.indx=item.split('-')[2];
                    ary=ary.map(it=>{
                    if(it.indx==item.split('-')[1]){//是该条
                      let obj=it;
                      obj.content.push(obj1);
                      return obj;
                    }else{
                      return it
                    }
                  })
                  }else{
                    flag=true;
                  }
                }
              });
              if(flag){
                message.warn('请完善常见内容')
                return
              }
              ary=ary.sort((a,b)=>a.indx-b.indx).map(item=>{
                let obj=item;
                delete obj.indx;
                return obj;
              });
 
             ary= ary.map(item=>{
                let obj=item;

                let content=item.content;
                content=content.sort((a,b)=>a.indx-b.indx).map(it=>it.content);
                obj.content=content;
                return obj;

              })
              params.commonProblem=JSON.stringify(ary)
            this.setState({ loading: true, saveLoading1: true }, () => {

              this.props.actions.upDateCommonproblem(params, () => {
                this.setState({ edit1: false, saveLoading1: false }, () => {
                  this.props.actions.getHotelConfig(() => {
                   this.setState({ loading: false, ary: JSON.parse(this.props.hotelDetail.commonProblem) })
                  })
                })
              },()=>{
                this.setState({loading:false,saveLoading1:false})
              })
            })
          }}>{GLOBAL_LOCALES['save']}</Button>
          <Button size="default" style={{ marginLeft: '10px' }} onClick={() => {
            this.setState({ edit1: false, ary: JSON.parse(this.props.hotelDetail.commonProblem) })
          }}>{GLOBAL_LOCALES['cancel']}</Button>
        </div>
      );
    } else {
      operate1 = <div className="shopping-operate i-icon" onClick={() => {
        let ary = this.state.ary;
        let obj = {}
        ary.forEach((item, index) => {
          obj['title' + '-' + index] = item.title;
          item.content.forEach((it, ind) => {
            obj['content' + '-' + index + '-' + ind] = it
          })
        })
        this.setState({ edit1: true }, () => {
          this.props.form.setFieldsValue(obj)
        })
      }}>{intl.get('lv.common.button.edit')}</div>;
    }

    return (
      <div className="shopping-work-container">
        <Loading display={this.state.loading ? 'block' : 'none'} />
        <div className='shopping-business-brief'>
          <div className='title'>业务简介</div>
          <div className='content'>
            <div className='row'>花筑旅行便利购隶属于旅悦（天津）酒店管理有限公司，是一家重构用户酒店住中服务消费体验的高科技零售小程序。花筑小店基于移动互联网和LBS定位技术，为用户提供近距离、住家式的消费场景，专注于提升客户服务，完善客户体验。 </div>
            <div className='row'>您可以在酒店大厅扫码购买，即时获取商品。也可以在房间里扫码进入花筑小店在线上选择购买，酒店会根据您的订单送货到房间。解决您在住店中的需求，享受花筑酒店带来的升级服务。</div>
          </div>
        </div>
        <div className='shopping-gap'></div>
        <div className='shopping-setting'>
          <div className='title'>门店设置 {operate}</div>
          <div className='content'>
            <div className='row' style={{ color: '#969FA3', fontWeight: '400', marginBottom: '20px' }}>
              设置售卖时间 * 在首页及用户在售卖时间段外下单时前端将给出提示
            </div>
            <div className='row'>
              <div className='row-content'>开始时间：
                {this.state.edit ?
                  <div>
                    <TimePicker
                      clear={false}
                      format={'HH:mm'}
                      value={this.state.startTime ? moment(this.state.startTime, 'HH:mm') : undefined}
                      onChange={this.onStartChange}
                      placeholder="开始时间" />
                  </div> :
                  <div>{this.props.hotelDetail.startTime}</div>}

              </div>
              <div className='row-content'>结束时间：
                {this.state.edit ?
                  <div>
                    <TimePicker
                      clear={false}
                      format={'HH:mm'}
                      value={this.state.endTime ? moment(this.state.endTime, 'HH:mm') : undefined}
                      onChange={this.onEndChange}
                      placeholder="结束时间" />
                  </div> :
                  <div>{this.props.hotelDetail.endTime}</div>}

              </div>
            </div>
          </div>
        </div>
        <div className='shopping-gap'></div>
        <div className='shopping-code'>
          <div className='title'>门店二维码</div>
          <div className='content'>
            {this.props.hotelDetail.qrCodes &&
              <div>
                <div className='row row-qrcode'>
                  <img src={this.props.hotelDetail.qrCodes.find(item => item.width == this.state.value).url} />
                  <Select
                    style={{ width: '135px' }}
                    value={this.state.value}
                    onChange={(value) => this.setState({ value: value })}
                  >
                    <Option value={'3'} >3CM²</Option>
                    <Option value={'5'} >5CM²</Option>
                    <Option value={'8'} >8CM²</Option>
                    <Option value={'11'} >11CM²</Option>
                  </Select>
                </div>
                <div className='row'>
                  <a target='_black' href={this.props.hotelDetail.qrCodes.find(item => item.width == this.state.value).url} download={this.props.hotelDetail.qrCodes.find(item => item.width == this.state.value).url}>
                    <Button size="default" type="primary" >下载</Button>
                  </a>

                </div>
              </div>


            }

          </div>
        </div>
        <div className='shopping-gap'></div>
        <div className='shopping-sell'>
          <div className='title'>销售员管理</div>
          <div className='content'>
            <div className='row' style={{
              marginBottom: '20px'
            }}><div className='add'
              onClick={() => {
                this.setState({ visible2: true })
              }}
            ><i className='i-icon'>&#xe638;</i>添加销售员</div></div>
            <Table
              rowKey="id"
              className='order-table'
              dataSource={this.props.sellerList}
              columns={this._renderTableColumns()}
              //onChange={this.handleTableChange}
              locale={
                {
                  emptyText: intl.get("lv.common.tips.no.data")
                }
              }
              pagination={false}
            />
          </div>
        </div>
        <div className='shopping-gap'></div>
        {this.props.hotelDetail.commonProblem && <div className='shopping-setting'>
          <div className='title'>常见问题 {operate1}</div>
          <div className='content'>
            <div className='row' style={{ color: '#969FA3', fontWeight: '400', marginBottom: '20px' }}>
              * 以下文案将展示在商品详情页最下端，请慎重修改！
            </div>
            {this.state.edit1 ? <div>
              {this.state.ary.map((item, index) => {
                return <div key={index} style={{ borderBottom: '1px solid #EAEAEA', marginBottom: '10px' }}>
                  <div className='row row-space'>
                    <FormItem
                      {...formItemLayout1}
                      label={'标题'}
                      required={true}
                    >
                      {getFieldDecorator('title' + '-' + index, )(
                        <Input placeholder='请输入标题' maxLength={30}/>
                      )}

                    </FormItem>
                    {index == 0 ? <div className='add'
                      onClick={() => {
                        let ary = this.state.ary;
                        let obj = { title: '', content: [''] };
                        ary = ary.concat(obj);
                        this.setState({ ary })
                      }}
                    ><i className='i-icon'>&#xe638;</i>添加常见问题</div> : <div className='add'
                      onClick={() => {
                        let ary = this.state.ary;
                        ary = ary.filter((it, indx) => indx != index
                        )
                        this.setState({ ary }, () => {
                          let obj = {}
                          ary.forEach((item, index) => {
                            obj['title' + '-' + index] = item.title;
                            item.content.forEach((it, ind) => {
                              obj['content' + '-' + index + '-' + ind] = it
                            })
                          })
                          this.props.form.setFieldsValue(obj)
                        })



                      }}
                    ><i className='i-icon'>&#xe63b;</i>删除常见问题</div>}
                  </div>
                  {item.content && item.content.map((it, ind) => <div key={ind} className='row row-space'>
                    <FormItem
                      {...formItemLayout1}
                      label={'描述'}
                      required={true}
                    >
                      {getFieldDecorator('content' + '-' + index + '-' + ind, )(
                        <TextArea 
                        maxLength={100}
                         style={{ 'resize': 'none' }} rows={6} placeholder={'请输入描述'} />
                      )}

                    </FormItem>
                    {ind == 0 ? <div className='add'
                      onClick={() => {
                        let ary = this.state.ary.map((content, conIndex) => {
                          if (conIndex == index) {
                            let obj = { ...content };
                            obj.content = content.content.concat('');
                            return obj;
                          } else {
                            return content
                          }
                        });
                        this.setState({ ary })
                      }}
                    ><i className='i-icon'>&#xe638;</i>添加问题描述</div> : <div className='add'
                      onClick={() => {
                        let ary = this.state.ary.map((content, conIndex) => {
                          if (conIndex == index) {
                            let obj = { ...content };
                            obj.content = content.content.filter((ite, indx) => ind !== indx);
                            return obj;
                          } else {
                            return content
                          }
                        });
                        this.setState({ ary }, () => {
                          let obj = {}
                          ary.forEach((item, index) => {
                            obj['title' + '-' + index] = item.title;
                            item.content.forEach((it, ind) => {
                              obj['content' + '-' + index + '-' + ind] = it
                            })
                          })
                          this.props.form.setFieldsValue(obj)
                        })
                      }}
                    ><i className='i-icon'>&#xe63b;</i>删除问题描述</div>}

                  </div>)}
                </div>
              })}
            </div> : <div>
                {this.state.ary.map((item, index) => {
                  return <div key={index}>
                    <div className='row'>{index + 1}、{item.title}</div>
                    {item.content && item.content.map((it, ind) => <div key={ind} className='row'>
                      {it}
                    </div>)}
                  </div>
                })}
              </div>}
          </div>
        </div>}






        {this.state.visible1 ? <Modal
          visible={this.state.visible1}
          onOk={this.commitChange1}
          onCancel={() => { this.setState({ visible1: false, id: null }) }}
          okText='确定'
          cancelText='取消'
          className='comment_pub_2'
          title="删除确认"
          maskClosable={false}
        >
          是否删除所选销售员？

        </Modal> : null}
        {this.state.visible2 ? <Modal
          visible={this.state.visible2}
          onOk={this.commitChange2}
          onCancel={() => { this.setState({ visible2: false, id: null }) }}
          okText='确定'
          cancelText='取消'
          className='comment_pub_2'
          title="添加销售员"
          maskClosable={false}
        >
          <FormItem
            {...formItemLayout}
            label={'姓名'}
          >
            {getFieldDecorator('sellerName', {
              rules: [{ required: true, message: '请输入姓名' }
              ],
            })(
              <Input placeholder='请输入姓名' maxLength={10}/>
              )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={'手机号'}
          >
            {getFieldDecorator('sellerPhoneNumber', {
              rules: [{ required: true, message: '请输入手机号' },
                , {
                validator: (rule, value, callback) => {
                  let reg = /^(\d+-?\d+)$/
                  if (reg.test(value) || value == undefined || value == "") {
                    callback()
                  } else {
                    callback('请输入正确的手机号')
                  }
                },
              }
              ],
            })(
              <Input placeholder='请输入手机号' />
              )}
          </FormItem>

        </Modal> : null}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.shopping,

  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch),

  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(List));
